import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import store from '../store/index';
import router from '../router/index';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

let messageErrorFn = (msg) => {
    Message.error(msg);
}

//线上地址
const baseURL = 'http://web.umfarm.com/ymfarm_web-1.0-SNAPSHOT/api';
// const baseURL = 'http://172.16.117.212:9090/api';
//测试地址 
// const baseURL = 'http://web.umubao.com/ymfarm_web-1.0-SNAPSHOT';
// const baseURL = 'http://10.10.0.106:8080'   //  海波地址
//本地地址 
// const baseURL = 'http://192.168.0.18:8080'; //永耀
// const baseURL = 'http://10.10.0.106:8080'; //海波

axios.defaults.baseURL = baseURL;

//是否打印请求返回值(打包上线时设为false)
// const showResponse = true;
const showResponse = false;

// 请求超时时间
axios.defaults.timeout = 5000;

// 跨域请求时是否需要使用凭证
axios.defaults.withCredentials = true;

// 添加请求拦截器
axios.interceptors.request.use(config => {
    NProgress.start();

    // 请求token
    if (store.getters.token) {
        config.headers.Authorization = store.getters.token;
    }

    if (Array.isArray(config.data)) {
        axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
    } else {
        if(config.url.indexOf('/bulletin/addOrUpdate') != -1) {
            axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
        }else{
            axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
            if (config.method === 'post') {
                config.data = qs.stringify(config.data);
            }
        }
        
    }
    return config;
}, error => {
    console.log(error);
    Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        NProgress.done();
        Message.closeAll();
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {            
            return Promise.reject(response);        
        }
    }, error => {
        NProgress.done();
        Message.closeAll();
        console.log("responseerr:" + error);
        messageErrorFn('网络请求错误，请稍后重试');
        return Promise.reject(error.response);
    });

// 请求成功处理函数
const httpSuccessFn = function(resolve, res){
    switch(res.data.code) {
        case -1:
            resolve(res.data);
            break;
        case 0:
            resolve(res.data);
            break;
        case 99:
            resolve(res);
            break;
        case -9994:
            resolve(res);
            break;
        case -9995:
            resolve(res);
            break;
        case -9997:
            resolve(res);
            break;
        case 40001:
            messageErrorFn(res.data.message);
            setTimeout(() => {
                router.replace({
                    path: '/'
                })
            }, 1000)
            break;
        default:
            messageErrorFn(res.data.message);
            break;
    }
}

const http = {
    /**
     * get方法，对应get请求
     * @param {String} url [请求的url地址]
     * @param {Object} params [请求时携带的参数]
     */
    get(url, params){    
        return new Promise((resolve, reject) =>{        
            axios.get(url, {            
                params: params        
            })
            .then(res => {
                if(showResponse){
                    console.log(`get ${url}`, res.data)
                }
                httpSuccessFn(resolve, res)
            })
            .catch(err =>{
                console.log('geterr:',err)
                if(err.status == 404){
                    messageErrorFn('请求的资源不存在');
                }else{
                    messageErrorFn('请求错误，请稍后重试');
                }
                // reject(err.data)
            })    
        });
    },

    /** 
     * post方法，对应post请求 
     * @param {String} url [请求的url地址] 
     * @param {Object} data [请求时携带的参数] 
     */
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios.post(url, data)
            .then(res => {
                if(showResponse){
                    console.log(`post ${url}`, res.data)
                }
                httpSuccessFn(resolve, res)
            })
            .catch(err =>{
                console.log('posterr:',err)
                if(err.status == 404){
                    messageErrorFn('请求的资源不存在');
                }else{
                    messageErrorFn('请求错误，请稍后重试');
                }
                // reject(err)
            })
        });
    }
}

export default http;